"use client";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import CommonSelector from "@/components/CommonSelector";
import EditModal from "@/components/EditModal";
import { STATUS } from "@/consts";
import { Label } from "@/components/ui/label";
import { useState, useEffect, useCallback } from "react";
import EmptyState from "@/components/EmptyState";

export default function CourtsManagement({
  campuses,
  getCourts,
  createCourt,
  updateCourt,
  deleteCourt,
}) {
  // 状态管理
  const [filteredCourts, setFilteredCourts] = useState([]);
  const [selectedCampus, setSelectedCampus] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');

  const searchCourts = useCallback(async () => {
    const courts = await getCourts({branch_campus_id: selectedCampus, status: selectedStatus});
    setFilteredCourts(courts);
  }, [selectedCampus,selectedStatus]);

  useEffect(() => {
    searchCourts();
  }, [searchCourts]);

  const CourtCard = ({ court }) => (
    <Card>
      <CardHeader>
        <CardTitle className="flex justify-between items-center">
          <p className="text-lg font-bold">{court.name}</p>
          <div className="flex gap-2">
            <EditModal
              title="编辑场地"
              onSubmit={updateCourt}
              onSuccess={searchCourts}
              trigger={
                <Button variant="ghost" size="icon">
                  <Pencil className="h-4 w-4 " />
                </Button>
              }
            >
              <CourtForm court={court} />
            </EditModal>
            <EditModal
              title="删除场地"
              onSubmit={deleteCourt}
              onSuccess={searchCourts}
              confirmButton="删除"
              trigger={
                <Button variant="ghost" size="icon">
                  <Trash2 className="h-4 w-4 text-red-500" />
                </Button>
              }
            >
              <p>确定要删除该场地吗？</p>
              <Input type="hidden" name="id" defaultValue={court.id} />
            </EditModal>
          </div>
        </CardTitle>
      </CardHeader>
      <CardContent>
        <p>
          <span className="font-medium">校区：</span>
          {campuses.find((campus) => campus.id === court.branch_campus_id)?.name}
        </p>
        <p>
          <span className="font-medium">状态：</span>
          {STATUS.find((status) => status.value === court.status)?.label}
        </p>
        <div>
          <span className="font-medium">备注：</span>
          <div className="mt-1">
            {court.memo && court.memo.trim().toLowerCase().startsWith('https://') ? (
              <a
                href={court.memo}
                target="_blank"
                rel="noopener noreferrer"
                className="text-blue-600 hover:text-blue-800 underline break-all text-sm"
                title={court.memo}
              >
                {court.memo.length > 50 ? `${court.memo.substring(0, 50)}...` : court.memo}
              </a>
            ) : (
              <span className="text-gray-700 break-words text-sm">
                {court.memo || '暂无备注'}
              </span>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );

  const CourtForm = ({ court }) => (
    <div className="space-y-4">
      <Input type="hidden" name="id" defaultValue={court?.id} />
      <div>
        <Label>校区</Label>
        <CommonSelector
          name="branch_campus_id"
          items={campuses.map((campus) => ({
            label: campus.name,
            value: campus.id,
          }))}
          defaultValue={court?.branch_campus_id}
        />
      </div>
      <div>
        <Label>场地名称</Label>
        <Input name="name" required defaultValue={court?.name} />
      </div>
      <div>
        <Label>场地状态</Label>
        <CommonSelector
          name="status"
          items={STATUS}
          defaultValue={court?.status || "active"}
        />
      </div>
      <div>
        <Label>备注</Label>
        <Input name="memo" required defaultValue={court?.memo} />
      </div>
    </div>
  );

  return (
    <div className="space-y-4 flex-1 flex flex-col p-6">
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold">场地管理</h1>
        <EditModal
          title="添加场地"
          onSubmit={createCourt}
          onSuccess={searchCourts}
          trigger={
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              <span>添加场地</span>
            </Button>
          }
        >
          <CourtForm />
        </EditModal>
      </div>

      {/* 筛选区域 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
        <div className="flex flex-row items-center gap-2">
          <Label className="w-24">校区</Label>
          <CommonSelector
            items={campuses.map((campus) => ({
              label: campus.name,
              value: campus.id,
            }))}
            defaultValue={selectedCampus}
            onValueChange={setSelectedCampus}
          />
        </div>
        <div className="flex flex-row items-center gap-2">
          <Label className="w-24">状态</Label>
          <CommonSelector
            items={[
              {
                label: '营业中',
                value: 'active',
              },
              {
                label: '暂停营业',
                value: 'inactive',
              },
            ]}
            defaultValue={selectedStatus}
            onValueChange={setSelectedStatus}
          />
        </div>
      </div>

      {/* 场地列表 */}
      {filteredCourts.length === 0 ? (
        <EmptyState message="没有找到符合条件的场地" />
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredCourts.map((court) => (
            <CourtCard key={court.id} court={court} />
          ))}
        </div>
      )}
    </div>
  );
}
